import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/exam/dto/assessment.response.dart';
import 'package:ichinesereader/exam/widgets/BGExamRecorder.dart';

import 'BGSinglePlayer.dart';

class BGExamTypeSpeech extends StatefulWidget {
  BGExamTypeSpeech(
      {Key? key,
      required this.item,
      this.questionId,
      required this.getFileIdAndAIScore})
      : super(key: key);
  final QuestionItem item;
  final String? questionId;
  final Function(String, int) getFileIdAndAIScore;

  @override
  State<BGExamTypeSpeech> createState() => _BGExamTypeSpeechState();
}

//验证是否包含特殊字符
bool isHaveSpecialCharacters(String input) {
  final reg = new RegExp(r'[`~!@#$%^&*()_+=|;:(){}'
      ',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？-]');
  return reg.hasMatch(input);
}

class _BGExamTypeSpeechState extends State<BGExamTypeSpeech>
    with SingleTickerProviderStateMixin {
  String _fileId = '';
  RxInt _score = (-1).obs;
  String _oldFileId = '';
  RxBool _isShowScore = false.obs;
  RxList _keywordsList = [].obs;

  @override
  Widget build(BuildContext context) {
    List<Widget> options = [];
    QuestionItem item = widget.item;
    if (item.answer != null && item.answer!.isNotEmpty) {
      _fileId = item.answer![0];
      _oldFileId = _fileId;
    }
    int? score = item.intelligenceScore;
    if (score != null && score > -1) {
      _score.value = score;
      _isShowScore.value = true;
    }

    options.add(Obx(() {
      return _buildSentenceWidget(_keywordsList);
    }));
    options.add(BGExamRecorder(
        fileId: _fileId,
        isRecognize: true,
        questionId: widget.questionId,
        number: item.number,
        getKeywords: (List keywordsList, int score) {
          _keywordsList.value = keywordsList;
          _score.value = score;
          _isShowScore.value = true;
        },
        getFileId: (String fileId) {
          _fileId = fileId;
        }));
    options.add(Obx(() {
      return _buildAIScoreWidget(_score.value);
    }));

    return Container(
        child: Column(
            crossAxisAlignment: CrossAxisAlignment.start, children: options));
  }

  String _getFeedback(int score) {
    if (0 <= score && score <= 10) return "Try your best! 🙈";
    if (10 < score && score <= 20) return "Don't give up! 🙅";
    if (20 < score && score <= 30) return "Don’t quit! 🐢";
    if (30 < score && score <= 40) return "You can do it! 💪";
    if (40 < score && score <= 50) return "Better next time! 😅";
    if (50 < score && score <= 60) return "Try again! 🏋";
    if (60 < score && score <= 65) return "Keep trying! 🏌";
    if (65 < score && score <= 70) return "On the right track! 🛤";
    if (70 < score && score <= 75) return "Getting there! 🚴";
    if (75 < score && score <= 80) return "Keep it up! 🏃";
    if (81 < score && score <= 85) return "Good work! 👏";
    if (85 < score && score <= 90) return "Great! 👍";
    if (90 < score && score <= 95) return "Super! 🌟";
    if (95 < score && score <= 98) return "Fantastic! 🏅";
    if (score == 99) return "Excellent! 🏆";
    if (score == 100) return "Perfect! 💎";
    return 'Try your best! 🙈';
  }

  Container _buildAIScoreWidget(int score) {
    if (_fileId.isNotEmpty && score > -1 && _oldFileId != _fileId) {
      _oldFileId = _fileId;
      widget.getFileIdAndAIScore(_fileId, score);
    }
    return Container(
        width: MediaQuery.of(Get.context!).size.width,
        padding: EdgeInsets.only(top: 15),
        child: Visibility(
            visible: _isShowScore.value,
            child: RichText(
                textAlign: TextAlign.center,
                text: TextSpan(
                    text: '${score.toString()}% ',
                    style: TextStyle(
                        fontSize: 26,
                        color: Color(0xFFD10303),
                        fontWeight: FontWeight.w600,
                        fontFamily: 'Noto Sans SC'),
                    children: [
                      TextSpan(
                          text: _getFeedback(score),
                          style: TextStyle(
                              fontSize: 26,
                              color: Colors.black,
                              fontWeight: FontWeight.w600,
                              fontFamily: 'Noto Sans SC'))
                    ]))));
  }

  Container _buildSentenceWidget(List keywordsList) {
    List<Widget> options = [];
    var head = widget.item.head;
    if (head != null && head.text != null) {
      String words = head.text ?? '';
      List<bool> wordsList = [];

      for (int i = 0; i < words.length; i++) {
        if (keywordsList.isNotEmpty) {
          if (keywordsList.length > i) {
            wordsList.add(keywordsList[i] == 1 ? true : false);
          }
        } else {
          wordsList.add(false);
        }
      }

      String showWords = head.text ?? '';
      for (int i = 0; i < showWords.length; i++) {
        String word = showWords[i];
        options.add(Text(word,
            style: TextStyle(
                fontSize: 26,
                color: (_fileId != '')
                    ? (wordsList[i] ? Color(0xFF4B9E63) : Color(0xFFCE5D4E))
                    : Colors.black,
                fontWeight: FontWeight.w500,
                fontFamily: 'Noto Sans SC')));
      }
    }

    options.add(Visibility(
        visible: head!.audio != null,
        child: Container(
            padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
            height: 36,
            width: 46,
            child: IconButton(
              iconSize: 36,
              padding: EdgeInsets.zero,
              icon: Icon(
                Icons.volume_up,
                color: Colors.orange,
              ),
              onPressed: () {
                BGSinglePlayer().play(head.audio);
              },
            ))));

    return Container(
        width: MediaQuery.of(Get.context!).size.width - 80,
        padding: EdgeInsets.only(bottom: 10),
        child: Wrap(runSpacing: 8, spacing: 6, children: options));
  }
}
